<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <!-- <TableData :config="table_config" :tableThead="tableThead" :dataList="dataList" :loading="loading"
        @selection-change="selectionChange">
        <template v-slot:inputPondId="{ row }">
          <span v-show="!row.inputPondId" class="successText">未使用</span>
          <span v-show="row.inputPondId" class="errorText">已使用</span>
        </template>
<template v-slot:fileId="{ row }">
          <el-image v-if="row.fileld" class="imageStyle" :src="row.imgUrl" :preview-src-list="[row.imgUrl]">
          </el-image>
          <span v-else>无二维码图片</span>
        </template>
</TableData> -->
      <div class="fishPondList">
        <div class="fishDataInfo" v-for="item, index in dataList" :key="index">
          <div class="fishImg">
            <el-image v-if="item.fileld" class="imageStyle" :src="item.pictureUrl" :preview-src-list="[item.pictureUrl]">
            </el-image>
          </div>
          <div class="info">
            <div class="ellipsis" :title="item.pondName">鱼塘名称:{{ item.pondName }}</div>
            <div class="ellipsis" :title="item.varietyName">养殖品种:{{ item.varietyName }}</div>
            <div class="ellipsis" :title="item.batchName">养殖批次:{{ item.batchName }}</div>
            <div class="ellipsis" :title="item.homeBaseName">所属基地:{{ item.homeBaseName }}</div>
            <div class="iconList">
              <i class="el-icon-edit icon" @click="handleRow(item, { flag: 'edit' })"></i>
              <i class="el-icon-delete icon" @click="handleRow(item, { flag: 'del' })"></i>
            </div>
          </div>
          <div class="code">
            <div class="codeImg">
              <el-image v-if="item.pictureId" style="width: 100%;height: 100%;" :src="item.imgUrl"
                :preview-src-list="[item.imgUrl]">
              </el-image>
            </div>
          </div>
        </div>
      </div>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="handleCurrentChange" :page="page" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <AddEdit :title="'二维码'" :fishPondList="fishPondList" @closeDialog="closeDialog" :addEditFlag="addEditFlag"
        :dialogVisible="dialogVisible" :data="formData">
      </AddEdit>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import SearchForm from '@/components-production-management/SearchForm';
import BtnSlot from '@/components-production-management/BtnSlot';
import TableData from '@/components-production-management/TableData';
import EnumSlot from '@/components-production-management/EnumSlot';
import AddEdit from './components/addEdit.vue';
//接口
import traceabilityQRCode from '@/api/quality-management/traceabilityQRCode.js';
//NC批次
import ncproductionApi from "@/api/production-management-nc/index";
import ncbasicinfoApi from "@/api/nc-basic-info/index";
export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot, AddEdit },
  data() {
    return {
      unfoldFlag: false,
      loading: false,
      dialogVisible: false,
      dialogVisible_lookView: false,
      addEditFlag: 'add',
      selectList: [],
      unitList: [],
      formData: {},
      page: 1,
      total: 10,
      selectIndex: 0,
      searchFormData: {},
      btnList: ['add', 'delete'],
      dataList: [],
      tableThead: [
        // { isShow: true, label: '批次编号', prop: 'batchName' },
        { isShow: true, label: '批次编号', prop: 'batchName' },
        { isShow: true, label: '养殖设施', prop: 'pondName' },
        { isShow: true, label: '二维码图片', slotName: 'fileId' },
        { isShow: true, label: '品种', prop: 'varietyName' }
      ],
      // 配置项
      table_config: {
        isCheckBox: true,

        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '编辑',
              type: 'primary',
              flag: 'edit',
              handleRow: this.handleRow
            },
            {
              label: '删除',
              type: 'danger',
              flag: 'del',
              handleRow: this.handleRow
            }
          ]
        },
      },
      formItemList: [
        {
          label: '养殖鱼塘',
          type: 'select',
          selectOptions: [],
          param: 'pondName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '养殖批次',
          type: 'select',
          selectOptions: [],
          param: 'batchName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '养殖品种',
          type: 'select',
          selectOptions: [],
          param: 'varietyName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }
      ],
      fishPondList: [],
      batchList: [],
      allbatchList: [],
      staffList: [],
      specificationList: [],
      fishVarietyList: [],
      breedTypeList: [],
      breedTypeObj: {}
    }
  },
  mounted() {
    this.queryPageByCondition();
    this.initData();
  },
  methods: {
    async initData() {
      let { data: fishPondList } = await ncproductionApi.queryInputPond({});
      let { data: fishVarietyList } = await ncbasicinfoApi.queryMaterial({ pk_parent: "1001A110000000003G58" })
      this.fishPondList = fishPondList || [];
      this.fishVarietyList = fishVarietyList || [];
      this.fishPondList = this.fishPondList.map(item => {
        return {
          ...item,
          pondName: item.cwarehousename,
        }
      })
      this.fishVarietyList = this.fishVarietyList.map(item => {
        return {
          ...item,
          varietyName: item.name,
        }
      })
      this.allbatchList = this.fishPondList.map(item => {
        return {
          ...item,
          batchName: item.vproductbatch,
        }
      })
      this.setFormOptions();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('pondName') !== -1) {
          let selectOptions = this.fishPondList.map(data => {
            return {
              text: data.pondName, value: data.pondName
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('varietyName') !== -1) {
          let selectOptions = this.fishVarietyList.map(data => {
            return {
              text: data.varietyName, value: data.varietyName
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('batchName') !== -1) {
          let selectOptions = this.allbatchList.map(data => {
            return {
              text: data.batchName, value: data.batchName
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };

      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    //批量删除
    delList(deleteList = [], key = 'traceSourceManagementId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await traceabilityQRCode.delListById(list);
        if (res.success) {
          this.$message.success(res.message || '删除成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.message || '删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //查询
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: 10,
        entity: {
          ...this.searchFormData
        }
      }
      this.loading = true;
      traceabilityQRCode.queryPageByCondition(params).then(res => {
        this.loading = false;
        if (res.success == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          this.dataList.forEach(item => {
            item.homeBaseName = sessionStorage.homeBaseName || '养殖基地',
              console.log(item.fileld)
            item.imgUrl = `${this.$baseurl.fileServiceUrl}base/files/preview?fileId=${item.fileld}`
            item.pictureUrl = `${this.$baseurl.fileServiceUrl}base/files/preview?fileId=${item.pictureId}`
          })
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.message || '分页查询失败')
        }
      }).catch(err => {
        this.loading = false;
        console.log(err)
      })
    },
    //搜索
    search(data) {
      this.page = 1;
      this.searchFormData = {
        ...this.searchFormData,
        ...data
      };
      this.queryPageByCondition();
    },
    //翻页查询
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    //查看详情
    lookView(row) {
      console.log(row)
      this.dialogVisible_lookView = true;
    },
    // table操作方法
    handleRow(rowData, item) {
      if (rowData.inputPondId) {
        this.$message.warning('该记录已使用')
        return
      }
      if (item.flag == 'edit') {
        this.dialogVisible = true;
        this.formData = JSON.parse(JSON.stringify(rowData))
      } else if (item.flag == 'del') {
        this.delList([rowData]);
      }
      this.addEditFlag = item.flag
    },
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag)
      if (flag == 'add') {
        this.dialogVisible = true
      } else if (flag == 'delete') {
        if (this.selectList.length > 0) {
          this.delList(this.selectList)
        } else {
          this.$message.warning('请先选择表单数据项后再删除！')
        }
      }
      this.addEditFlag = flag
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryPageByCondition();
    },
  }
};
</script>
<style lang="scss" scoped>
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.imageStyle {
  height: 240px;
  width: 240px;
  border-radius: 10px;
  background-color: #91d0dc;
}

.fishPondList {
  min-width: 1590px;
  display: flex;
  justify-content: flex-start;

  .fishDataInfo {
    width: calc(50% - 20px);
    margin: 10px;
    padding: 20px;
    box-shadow: 0 5px 15px 10px #0000002c;
    background-image: url("~@/assets/haibg.png");
    border-radius: 10px;
    display: flex;
    justify-content: flex-start;
    transition: all 0.3s;

    .info {
      width: 300px;
      height: 240px;
      color: #333333;
      font-size: 18px;
      padding: 20px;
      padding-right: 0;
      line-height: 38px;
      background-color: #ffffffc6;
      margin-left: 20px;
      border-radius: 10px 0 0 10px;

      .iconList {
        width: 50px;
        padding-top: 10px;
        display: flex;
        opacity: 0;
        transition: all 0.3s;

        .icon {
          padding-right: 5px;
          cursor: pointer;
        }

        .el-icon-edit {
          color: blue;
        }

        .el-icon-delete {
          color: red;
        }
      }
    }

    &:hover {
      transform: translateY(-5px);

      .iconList {
        opacity: 1;
      }
    }

    .code {
      width: 200px;
      height: 240px;
      background-color: #ffffffc6;
      display: flex;
      align-items: center;

      border-radius: 0 10px 10px 0;

      .codeImg {
        background-color: #3333332d;
        width: 160px;
        height: 160px;
      }
    }
  }
}
</style>